import api from './myaxios'
import tokenService from '@/auth/tokenManage'
import axios from 'axios'
const refreshApi = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
})
export default {
  /**
   * 用户登录方法
   * @param {string} username - 用户名
   * @param {string} password - 密码
   * @returns {Promise<Object>} - 登录成功后的响应数据
   */
  async login(username, password) {
    try {
      const response = await api.post('/api/login/', { username, password })
      tokenService.setTokens(response.data.access, response.data.refresh)
      return response.data
    } catch (error) {
      // 在生产环境中，可以使用专业的日志记录工具
      const errorData = error.response?.data || {}

      // 提取可读错误信息
      const userMessage = errorData.message || errorData.detail || '登录失败，请检查凭证'

      // 抛出标准化错误对象
      throw {
        message: userMessage,
        code: errorData.code || 'UNKNOWN_ERROR',
        status: error.response?.status,
        original: errorData, // 保留原始错误信息
        error: error,
      }
    }
  },

  async refreshToken() {
    const refreshToken = tokenService.getRefreshToken()
    try {
      const response = await refreshApi.post('/api/refresh/', {
        refresh: refreshToken,
      })
      tokenService.setAccessTokens(response.data.access)

      return response.data.access
    } catch (error) {
      console.error('刷新Token失败:', error)
      tokenService.clearTokens()
      throw error
    }
  },

  async fetchChoices() {
    try {
      const response = await api.get('/api/choices')
      return response.data
    } catch (error) {
      console.error('Error fetching choices:', error)
      throw error
    }
  },
  async uploadData(form) {
    try {
      const response = await api.post('/api/surveys/', form, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      return response.data
    } catch (error) {
      console.error('Error uploading datas:', error)
      throw error
    }
  },
  //获取数据
  async fetchData(params) {
    try {
      const response = await api.get(`/api/cultural-relics/`, { params })
      return response
    } catch (error) {
      console.error('Error uploading datas:', error)
      throw error
    }
  },
  // 详情请求
  async fetchDetail(id) {
    return api.get(`/api/cultural-relics/${id}/`)
  },

  // 更新请求
  async updateRelic(id, data) {
    return api.put(`/api/cultural-relics/${id}/`, data)
  },

  // 删除请求
  async deleteRelic(id) {
    return api.delete(`/api/cultural-relics/${id}/`)
  },
  // src/api/fileDownload.js

  async downloadFile(fileType, relicId, fileName = '', imageId = '') {
    try {
      // 构建下载URL（根据不同类型调整路径）
      let url = ''
      if (fileType === 'disease_image' && imageId !== null) {
        // 病害图片带ID的URL（新逻辑）
        url = `/api/cultural-relics/${relicId}/download-image/${fileType}/${imageId}/`
      } else if (['image', 'disease_image'].includes(fileType)) {
        // 主图或默认病害图（保持向后兼容）
        url = `/api/cultural-relics/${relicId}/download-image/${fileType}/`
      } else {
        url = `/api/download/${fileType}/${relicId}/`
      }

      // 发送下载请求
      const response = await api.get(url, {
        responseType: 'blob', // 以blob形式接收文件数据
      })

      // 解析文件名（优先使用响应头，其次使用默认名）
      let filename = fileName || 'unknown-file'
      const contentDisposition = response.headers['content-disposition']
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename\*?=['"]?([^'";]+)['"]?/i)
        if (filenameMatch && filenameMatch[1]) {
          // 处理UTF-8编码的文件名（RFC 6266标准）
          if (contentDisposition.includes('filename*=UTF-8')) {
            filename = decodeURIComponent(filenameMatch[1])
          } else {
            // 处理普通文件名（可能包含中文）
            filename = filenameMatch[1].replace(/\\/g, '').replace(/"/g, '')
          }
        }
      }

      // 获取MIME类型
      const contentType = response.headers['content-type'] || 'application/octet-stream'

      // 处理图片类型的特殊逻辑（可选，根据需求调整）
      const isImage = ['image/jpeg', 'image/png', 'image/gif'].some((type) =>
        contentType.startsWith(type),
      )

      // 创建Blob对象
      const blob = new Blob([response.data], { type: contentType })

      // 创建下载链接
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = filename

      // 触发下载
      document.body.appendChild(link)
      link.click()

      // 清理资源
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)

      // 返回成功结果
      return {
        success: true,
        filename,
        size: blob.size,
        isImage,
      }
    } catch (error) {
      console.error('文件下载失败:', error)
      let errorMessage = '下载失败，请重试'

      // 解析HTTP错误响应
      if (error.response) {
        const { status, data } = error.response
        errorMessage = data?.detail || errorMessage

        switch (status) {
          case 404:
            errorMessage = '文件不存在'
            break
          case 403:
            errorMessage = '无权限下载该文件'
            break
          case 400:
            errorMessage = '请求参数错误'
            break
          case 500:
            errorMessage = '服务器内部错误'
            break
        }
      } else if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络'
      }

      // 返回错误结果
      return {
        success: false,
        error: errorMessage,
      }
    }
  },
  async deleteDiseaseImage(relicId, imageId) {
    try {
      // 显示确认对话框
      if (!window.confirm('确定要删除图像吗？此操作不可恢复')) {
        return
      }

      // 发送删除请求
      const url = `/api/cultural-relics/${relicId}/delete-image/disease_image/${imageId}/`
      await api.delete(url)

      // 返回成功结果
      return { success: true }
    } catch (error) {
      console.error('删除病害图片失败:', error)

      // 解析错误信息
      let errorMessage = '删除失败，请重试'
      if (error.response) {
        const { status, data } = error.response
        errorMessage = data?.detail || errorMessage

        switch (status) {
          case 404:
            errorMessage = '图片不存在或已被删除'
            break
          case 403:
            errorMessage = '无权限删除此图片'
            break
          case 500:
            errorMessage = '服务器错误，删除失败'
            break
        }
      } else if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络'
      }

      // 显示错误提示
      this.$message.error(errorMessage)

      // 返回错误结果
      return { success: false, error: errorMessage }
    }
  },
  async createCategory(formData) {
    return api.post('/api/categories/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 上传文件必须设置
      },
    })
  },
  fetchCategories: async (params = {}) => {
    return api.get('/api/categories/', {
      params, // 直接传递查询参数
      headers: {
        'Content-Type': 'application/json', // 常规JSON请求
      },
    })
  },
  deleteCategory: async (id) => {
    return api.delete(`/api/categories/${id}/`, {
      headers: {
        'Content-Type': 'application/json', // 常规JSON请求
      },
    })
  },
  fetchCategoryDetail: async (id) => {
    return api.get(`/api/categories/${id}/`) // 直接调用，不设置headers
  },
  updateCategory: async (id, formData) => {
    try {
      const response = await api.put(`/api/categories/${id}/`, formData, {
        headers: {
          // 关键：让浏览器自动设置Content-Type为multipart/form-data
          // 不要手动设置，否则会破坏boundary
          'Content-Type': 'multipart/form-data',
        },
      })
      return response.data
    } catch (error) {
      console.error('更新类别失败:', error)
      throw error // 将错误抛给调用者处理
    }
  },
  async compareDiseaseImages(payload) {
    try {
      // 验证参数
      if (!payload || !payload.relic_id || !payload.image_ids || payload.image_ids.length !== 2) {
        throw new Error('参数错误：需要提供文物ID和两张图片ID')
      }

      // 发送对比请求
      const response = await api.post(`/api/compare_disease_images/`, {
        image_ids: payload.image_ids,
        relic_id: payload.relic_id,
      })

      // 返回标准化的响应数据
      return response
    } catch (error) {
      console.error('图片比对失败:', error)

      // 解析错误信息
      let errorMessage = '比对失败，请重试'
      if (error.response) {
        const { status, data } = error.response

        // 根据HTTP状态码和后端返回的错误信息定制提示
        errorMessage = data?.detail || errorMessage

        switch (status) {
          case 400:
            errorMessage = '参数错误：请检查图片ID是否正确'
            break
          case 404:
            errorMessage = '图片不存在或已被删除'
            break
          case 403:
            errorMessage = '无权限进行图片比对'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
        }
      } else if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络'
      }

      // 抛出标准化的错误对象
      throw {
        message: errorMessage,
        code: error.response?.status || 'UNKNOWN_ERROR',
        original: error,
      }
    }
  },
  logout() {
    tokenService.clearTokens()
  },
}
